/*
    曲线页面
*/
//展开与收缩
    var flag = true;//??
    $('.toogle-list i').click(function(){
        // var flag = true;
        if(flag){
            $(this).removeClass('glyphicon-minus').addClass('glyphicon-plus').parent().siblings().slideUp()
            flag = false;
        }else {
            $(this).removeClass('glyphicon-plus').addClass('glyphicon-minus').parent().siblings().slideDown()
            flag = true;
        }

        console.log(flag)
        
    })

//获得曲线数据
    function getSendData(){
        var deviceid = $("#device-id").val() == "" ? null : $("#device-id").val(),
            starttime = $("#start-time").val() == "" ? null : $("#start-time").val(),
            endtime = $("#end-time").val() == "" ? null : $("#end-time").val();
        var data = {deviceid: deviceid, timefrom: starttime, timeto: endtime};
        return data;
    }
    socket.on('connect', function () {
        console.log("connected!");
        $("#chartTimeBtn").click(function(){
            // $("#chartInfo").hide();
            var data = getSendData();
            //请求 历史曲线 数据
            socket.emit('curve_history',data);
        })
    });
    //原始曲线data 可能是多个设备，可能是一个设备
    var originData = []; 
    //目标曲线data 适合flot的数据格式
    var aimData = [];  
    socket.on("curve_history_return",function(data){
        // console.log(data);
        // data:{temp:"xx",press:"xx",time:"xx"};

        var newdata = {name: $("#device-id").val(), origin: data }
        originData.push(newdata);
        console.log(originData); // 所有获得的原始数据
        aimData = [];
        for(var i=0; i<originData.length; i++) {//原始数据循坏
            var device = originData[i];//设备数据 name & origin
            var origin = originData[i].origin; //设备曲线原始数据
            
            var press = {}, temp = {};//目标设备的压力和曲线
            press.label = originData[i].name + "压力";
            temp.label = originData[i].name + "温度";
            var pressData = [], tempData= [];
            for(var j=0; j<origin.length; j++){ 
                var time = (new Date(origin[j].time + ' 00:00:00')).getTime();//时间毫秒
                pressData[j] = [time, origin[j].press];
                press.data = pressData;//压力值

                tempData[j] = [time, origin[j].temp];
                temp.data = tempData;//温度值
            }
            press.yaxis = 1;
            temp.yaxis = 2;

            aimData.push(press)
            aimData.push(temp)
            // console.log(aimData)
            
        }
        
        // console.log(aimData)
        set_chart(aimData);
    
    });
//曲线显示     
    function set_chart(aimData) {

        var datasets = aimData;
        //曲线颜色
        var i = 0;
        $.each(datasets, function(key, val) {
            val.color = i;
            ++i;
        });
        // 添加checkbox 
        var choiceContainer = $(".chart-option");
        choiceContainer.html('');//清除选项框的内容
        $.each(datasets, function(key, val) {
            choiceContainer.append(
                `<li>
                    <label>
                        <input type="checkbox" name="`+key+`" checked="checked" id="id`+key+`">
                        <span class="glyphicon glyphicon-stats"></span>
                        <span for="id`+key+`">`+val.label+`</span>
                    </label>
                </li>`
            );
        });

        choiceContainer.find("input").click(plotAccordingToChoices);

        function plotAccordingToChoices() {

            var data = [];

            choiceContainer.find("input:checked").each(function () {
                var key = $(this).attr("name");
                if (key && datasets[key]) {
                    data.push(datasets[key]);
                }
            });
            if (data.length > 0) {
                var plot = $.plot("#deviceAllChart", data, {
                    series: {
                        lines: { show: true,
                                 lineWidth: 2,
                            },
                        points: { show: true },
                        shadowSize: 2
                    },
                    grid: { hoverable: true, 
                           clickable: true, 
                           tickColor: "#dddddd",
                           borderWidth: 2 
                    },
                    yaxis: {
                        // position:"left" //y轴默认在左边
                        tickDecimals: 2 //y轴小数点位数
                    },
                    xaxis: {
                        mode: "time", //x轴显示时间数据格式
                        tickSize:[1, "day"], //刻度标签会以每1天的间隔显示
                        timeformat: "%Y/%m/%d", //刻度标签要输出的格式
                        rotateTicks: 45, //jquery.flot.tickrotor 控制x轴过长时的倾斜
                        labelWidth: 150,
                        labelHeight: 150,
                        reserveSpace: true,
                        tickDecimals: 0 //x轴小数点位数
                    },
                    legend: {
                        noColumns: 0,
                            labelFormatter: function (label, series) {
                                return "<font size=\"2\" color=\"white\">" + label + "</font>";
                        },            
                        backgroundColor: "#000",
                        backgroundOpacity: 0.9,
                        labelBoxBorderColor: "#000000",
                        position: "nw"
                    }
                });

                function showTooltip(x, y, contents) {
                    $('<div id="tooltip">' + contents + '</div>').css( {
                        position: 'absolute',
                        display: 'none',
                        top: y + 5,
                        left: x + 5,
                        border: '1px solid #fdd',
                        padding: '2px',
                        'background-color': '#dfeffc',
                        opacity: 1,
                        'z-index': 1000
                    }).appendTo("body").fadeIn(200);
                }

                var previousPoint = null;
                $("#deviceAllChart").bind("plothover", function (event, pos, item) {
                    $("#x").text(pos.x);
                    $("#y").text(pos.y.toFixed(2));

                        if (item) {
                            if (previousPoint != item.dataIndex) {
                                previousPoint = item.dataIndex;

                                $("#tooltip").remove();
                                var x = new Date(item.datapoint[0]).toLocaleString(),//时间戳毫秒数转换成日期时间
                                    y = item.datapoint[1].toFixed(2);

                                showTooltip(item.pageX, item.pageY,
                                            item.series.label + " 在 " + x + " 的值是 " + y);
                            }
                        }
                        else {
                            $("#tooltip").remove();
                                previousPoint = null;
                        }
                    }); 
                }
            }

        plotAccordingToChoices();
    }
